import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import '../models/word_card.dart';
import '../models/word_book.dart';
import '../data/word_book_service.dart';
import '../widgets/word_card_widget.dart';
import 'dart:async';
import 'dart:math';

class ChallengePage extends StatefulWidget {
  final WordBook wordBook;
  final List<WordCard> words;

  const ChallengePage({
    Key? key,
    required this.wordBook,
    required this.words,
  }) : super(key: key);

  @override
  _ChallengePageState createState() => _ChallengePageState();
}

class _ChallengePageState extends State<ChallengePage> {
  final AudioPlayer _audioPlayer = AudioPlayer();
  int _currentIndex = 0;
  bool _showDetails = false;
  bool _isRecording = false;
  bool _isAnswerCorrect = false;
  bool _hasAnswered = false;
  Timer? _recordingTimer;
  List<double> _audioWaveform = [];
  
  @override
  void initState() {
    super.initState();
    if (widget.words.isNotEmpty) {
      _playWhatsThis();
    }
  }

  @override
  void dispose() {
    _audioPlayer.dispose();
    _recordingTimer?.cancel();
    super.dispose();
  }

  void _playWhatsThis() {
    _audioPlayer.play(AssetSource('data/audio/whats-this.mp3'));
  }

  void _playWordAudio() {
    if (_currentIndex >= widget.words.length) return;
    
    final WordCard word = widget.words[_currentIndex];
    _audioPlayer.play(UrlSource('https://ali.bczcdn.com/r/${word.wordAudio}'));
  }

  void _startRecording() {
    if (_isRecording) return;
    
    setState(() {
      _isRecording = true;
      _audioWaveform = [];
    });
    
    // 模拟录音波形
    _recordingTimer = Timer.periodic(Duration(milliseconds: 100), (timer) {
      if (_audioWaveform.length < 50) {
        setState(() {
          _audioWaveform.add(Random().nextDouble());
        });
      }
    });
  }

  void _stopRecording() {
    _recordingTimer?.cancel();
    
    setState(() {
      _isRecording = false;
      _showDetails = true;
      _hasAnswered = true;
    });
    
    // 模拟语音识别结果
    _checkAnswer();
    _playWordAudio();
  }

  void _checkAnswer() {
    // 这里应该实现实际的语音识别和波形比较
    // 现在只是随机生成结果作为示例
    final bool isCorrect = Random().nextBool();
    
    setState(() {
      _isAnswerCorrect = isCorrect;
    });
    
    if (!isCorrect) {
      _moveWordToNew();
      _showIncorrectNotification();
    }
  }

  void _moveWordToNew() async {
    if (_currentIndex >= widget.words.length) return;
    
    final WordCard word = widget.words[_currentIndex];
    await WordBookService.moveWordToNew(widget.wordBook.id, word.word);
  }

  void _showIncorrectNotification() {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('单词已移动至新词词库'),
        backgroundColor: Colors.red,
        duration: Duration(seconds: 2),
      ),
    );
  }

  void _moveToNextWord() {
    setState(() {
      _currentIndex++;
      _showDetails = false;
      _hasAnswered = false;
      _audioWaveform = [];
    });
    
    if (_currentIndex < widget.words.length) {
      _playWhatsThis();
    } else {
      // 所有单词都已学习完毕
      _showCompletionDialog();
    }
  }

  void _showCompletionDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text('恭喜！'),
        content: Text('您已完成本轮挑战。'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(); // 关闭对话框
              Navigator.of(context).pop(); // 返回上一页
            },
            child: Text('返回'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (widget.words.isEmpty || _currentIndex >= widget.words.length) {
      return Scaffold(
        appBar: AppBar(
          title: Text('挑战模式'),
        ),
        body: Center(
          child: Text('没有更多单词了'),
        ),
      );
    }

    final WordCard currentWord = widget.words[_currentIndex];

    // 录音按钮或结果指示
    Widget recordButton;
    if (_hasAnswered) {
      // 显示答案结果
      recordButton = Container(
        width: 60,
        height: 60,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: _isAnswerCorrect ? Colors.green : Colors.red,
        ),
        child: Icon(
          _isAnswerCorrect ? Icons.check : Icons.close,
          color: Colors.white,
          size: 30,
        ),
      );
    } else if (_isRecording) {
      // 显示录音波形
      recordButton = GestureDetector(
        onTapUp: (_) => _stopRecording(),
        child: Container(
          height: 60,
          width: 200,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(30),
            color: Colors.blue,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              for (int i = 0; i < _audioWaveform.length; i += 3)
                if (i < _audioWaveform.length)
                  Container(
                    margin: EdgeInsets.symmetric(horizontal: 1),
                    width: 3,
                    height: 20 + _audioWaveform[i] * 20,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(1.5),
                    ),
                  ),
            ],
          ),
        ),
      );
    } else {
      // 显示录音按钮
      recordButton = GestureDetector(
        onTapDown: (_) => _startRecording(),
        child: Container(
          width: 60,
          height: 60,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Colors.blue,
          ),
          child: Icon(
            Icons.mic,
            color: Colors.white,
            size: 30,
          ),
        ),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('挑战模式'),
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.blue.withOpacity(0.3),
              Colors.purple.withOpacity(0.3),
            ],
          ),
        ),
        child: Column(
          children: [
            // 单词卡片
            Expanded(
              child: Container(
                margin: EdgeInsets.all(16),
                child: WordCardWidget(
                  wordCard: currentWord,
                  showDetails: _showDetails,
                  onTap: () {
                    if (!_showDetails) {
                      setState(() {
                        _showDetails = true;
                      });
                      _playWordAudio();
                    }
                  },
                  bottomActions: Center(child: recordButton),
                ),
              ),
            ),
            
            // 导航按钮
            if (_hasAnswered)
              Padding(
                padding: EdgeInsets.all(16),
                child: ElevatedButton(
                  onPressed: _moveToNextWord,
                  style: ElevatedButton.styleFrom(
                    padding: EdgeInsets.symmetric(horizontal: 40, vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                  ),
                  child: Text(
                    '下一个',
                    style: TextStyle(fontSize: 18),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
} 